<template>
    <div class="login">
        <h1>登录</h1>
        <el-form ref="loginform" :rules="rules" :model="form" label-width="80px">
            <el-form-item label="用户名" prop="username">
                <el-input placeholder="请输入用户名" v-model="form.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input placeholder="请输入密码" v-model="form.password" show-password></el-input>
            </el-form-item>
        </el-form>
        <el-button type="primary" @click="login">主要按钮</el-button>
    </div>
</template>

<script>
import { Login } from '@/api/user';
import axios from 'axios';

export default {
    data() {
        return {
            form: {
                username: '',
                password: '',
            },
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                ],
            }
        }
    },
    methods: {
        login() {
            // 前置拦截
            this.$refs['loginform'].validate( async (valid) => {
                if(valid) {
                    // 前置验证通过后执行代码
                    console.log(this.form);
                    // 发起请求
                    // 发起一个post请求
                    let {data,meta} = await Login(this.form)
                    console.log(data,meta);
                    // 什么时候跳转 有token的时候
                    if(meta.status!=200) return this.$message.error(meta.msg)
                    // 成功
                    localStorage.setItem('admin_token',data.token)
                    
                    this.$router.push('/')
                    
                }

            })

        }
    }

}
</script>

<style scoped>
.login {
    width: 400px;
    height: 400px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border: 1px solid;
    border-radius: 15px;
    box-shadow: 0px 0px 20px 0px greenyellow;
    padding: 20px;
    box-sizing: border-box;
    text-align: center
}

h1 {
    text-align: center;
    color: purple;
}
</style>